package com.tanhua.server.service;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VoiceApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Voice;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.VoiceVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class ReachblossomService {
    @DubboReference
    private VoiceApi voiceApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //发送语音
    public void sendVoices(MultipartFile voiceFile) throws IOException {
        //判空
        if (voiceFile.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }
        //1、将音频上传到FastDFS,获取访问URL
        String filename = voiceFile.getOriginalFilename();  // abc.mp4
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = fastFileStorageClient.uploadFile(voiceFile.getInputStream(), voiceFile.getSize(), filename, null);
        String vioceUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //2.构建Voice对象
        Voice voice = new Voice();
        voice.setUserId(UserHolder.getUserId());
        voice.setVoiceUrl(vioceUrl);
        //3.调用api保存数据
        String voiceId = voiceApi.save(voice);
        if (StringUtils.isEmpty(voiceId)) {
            throw new BusinessException(ErrorResult.error());
        }
        //4.查询redis获取今日发送次数
        String key = Constants.REST_SEND_COUNY + UserHolder.getUserId();
        String count = redisTemplate.opsForValue().get(key);
        if(count == null) {
            redisTemplate.opsForValue().set(key, 9 + "", 1, TimeUnit.DAYS);
        } else {
            redisTemplate.opsForValue().set(key, String.valueOf(Integer.valueOf(count)-1), 1, TimeUnit.DAYS);
        }
        if(Integer.valueOf(count) <= 0) {
            throw new BusinessException(ErrorResult.error());
        }
    }

    //接收语音
    public VoiceVo acceptVoice() {
        //1.查询mongo数据库中voice表，随机获取语音消息url
        Voice voice = voiceApi.findRandom();
        String voiceUrl = voice.getVoiceUrl();
        //2.查询用户信息表，获取用户基本信息
        UserInfo userInfo = userInfoApi.findById(voice.getUserId());
        //判空
        if (userInfo == null) {
            throw new BusinessException(ErrorResult.error());
        }
        //对象复制
        VoiceVo voiceVo = VoiceVo.init(userInfo, voice);
        //3.查询剩余次数(用户剩余次数从redis中获取)
        String key = Constants.REST_ACCEPT_COUNT + UserHolder.getUserId();
        String count = redisTemplate.opsForValue().get(key);
        if (count == null) {
            redisTemplate.opsForValue().set(key, 9 + "", 1, TimeUnit.DAYS);
        } else {
            redisTemplate.opsForValue().set(key, String.valueOf(Integer.valueOf(count) - 1), 1, TimeUnit.DAYS);
            if (Integer.valueOf(count) <= 0) {
                throw new BusinessException(ErrorResult.error());
            }
            voiceVo.setRemainingTimes(Integer.valueOf(count));
        }
        //4.封装VoiceVo对象，返回
        voiceVo.setVoiceUrl(voiceUrl);
        return voiceVo;
    }
}
